import { reactive } from 'vue'
import { defaultShortCuts } from '@/constants'
import { eventBus, logger } from '@/instance'
import { EventComposition } from '@/types'

export type ShortcutComposition = {
  shortcuts: typeof defaultShortCuts,
} & EventComposition

export function useShortcuts(): ShortcutComposition {
  logger.log('composables/shortcuts', 'useShortcuts')
  const shortcuts = reactive(defaultShortCuts)

  const keyDownHandler = (e: KeyboardEvent) => {
    e.preventDefault()
    const hitedEvents = shortcuts.filter(i => {
      return i.ctrlKey === e.ctrlKey && i.shiftKey === e.shiftKey && i.metaKey === e.metaKey && i.key === e.key
    })
    hitedEvents.forEach(i => eventBus.emit(i.action as string, e))
    logger.log('composables/shortcuts', 'keyDownHandler', e, hitedEvents)
  }
  const bind = () => {
    document.addEventListener('keydown', keyDownHandler)
    logger.log('composables/shortcuts', 'bind')
  }
  const unbind = () => {
    document.removeEventListener('keydown', keyDownHandler)
    logger.log('composables/shortcuts', 'unbind')
  }



  return { shortcuts, bind, unbind }
}